/*
 * Created on 2005-7-11
 *
 */
package com.et114.components.ldap4oj.support;

import org.springframework.beans.factory.InitializingBean;




import javax.naming.NamingException;
import javax.naming.directory.DirContext;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.dao.DataAccessResourceFailureException;

public class RelativeContextSource implements ContextSourceInterface,
        InitializingBean {

    private ContextSourceInterface baseContextSource = null;

    private String relativeName = "";

    protected final Log logger = LogFactory.getLog(getClass());

    /**
     * @return Returns the baseContextSource.
     */
    public ContextSourceInterface getBaseContextSource() {
        return baseContextSource;
    }

    /**
     * @param baseContextSource
     *            The baseContextSource to set.
     */

    public void setBaseContextSource(ContextSourceInterface baseContextSource) {
        this.baseContextSource = baseContextSource;
    }

    /**
     * @return Returns the relativeName.
     */
    public String getRelativeName() {
        return relativeName;
    }

    /**
     * @param relativeName
     *            The relativeName to set.
     */
    public void setRelativeName(String relativeName) {
        this.relativeName = relativeName;
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.springframework.ldap.support.ContextSourceInterface#getDirContext()
     */
    public DirContext getDirContext() {
        try {
            return (DirContext) getBaseContextSource().getDirContext().lookup(
                    getRelativeName());
        } catch (NamingException e) {
            String baseName = "Can not get basename";
            try {
                baseName = getBaseContextSource().getDirContext()
                        .getNameInNamespace();
            } catch (NamingException ex) {
                logger.warn("Can not get basename", ex);
            }
            throw new DataAccessResourceFailureException(
                    "Can not get relative context (base = " + baseName
                            + " , relative name = " + getRelativeName(), e);
        }
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
     */
    public void afterPropertiesSet() throws Exception {
        if (getBaseContextSource() == null) {
            logger.error("baseContextSource null");
        }
    }

}
